using HtmlAgilityPack;
using System.Text.RegularExpressions;

namespace DaoHang.Services
{
    /// <summary>
    /// 网站信息获取服务实现类
    /// </summary>
    public class WebsiteInfoService : IWebsiteInfoService
    {
        private readonly HttpClient httpClient;
        private readonly ILogger<WebsiteInfoService> logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpClient">HTTP客户端</param>
        /// <param name="logger">日志记录器</param>
        public WebsiteInfoService(HttpClient httpClient, ILogger<WebsiteInfoService> logger)
        {
            this.httpClient = httpClient;
            this.logger = logger;
            
            // 配置HTTP客户端
            this.httpClient.Timeout = TimeSpan.FromSeconds(10);
            this.httpClient.DefaultRequestHeaders.Add("User-Agent", 
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        }

        /// <summary>
        /// 根据URL获取网站信息
        /// </summary>
        /// <param name="url">网站URL</param>
        /// <returns>网站信息</returns>
        public async Task<WebsiteInfo> GetWebsiteInfoAsync(string url)
        {
            var websiteInfo = new WebsiteInfo();

            try
            {
                // 验证和标准化URL
                if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
                {
                    // 尝试添加http://前缀
                    if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                    {
                        url = "http://" + url;
                        if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
                        {
                            websiteInfo.ErrorMessage = "无效的URL格式";
                            return websiteInfo;
                        }
                    }
                    else
                    {
                        websiteInfo.ErrorMessage = "无效的URL格式";
                        return websiteInfo;
                    }
                }

                // 获取网页内容
                var response = await httpClient.GetAsync(uri);
                if (!response.IsSuccessStatusCode)
                {
                    websiteInfo.ErrorMessage = $"无法访问网站: {response.StatusCode}";
                    return websiteInfo;
                }

                var html = await response.Content.ReadAsStringAsync();
                
                // 解析HTML
                var doc = new HtmlDocument();
                doc.LoadHtml(html);

                // 获取网站标题
                websiteInfo.Title = GetWebsiteTitle(doc, uri);

                // 获取网站描述
                websiteInfo.Description = GetWebsiteDescription(doc);

                // 获取网站图标
                websiteInfo.IconUrl = await GetWebsiteIconAsync(doc, uri);

                // 获取网站内容（用于AI分析）
                websiteInfo.Content = GetWebsiteContent(doc);

                websiteInfo.Success = true;
                logger.LogInformation("成功获取网站信息: {Url} - {Title}", url, websiteInfo.Title);
            }
            catch (TaskCanceledException)
            {
                websiteInfo.ErrorMessage = "请求超时，请检查网站是否可访问";
                logger.LogWarning("获取网站信息超时: {Url}", url);
            }
            catch (HttpRequestException ex)
            {
                websiteInfo.ErrorMessage = $"网络请求失败: {ex.Message}";
                logger.LogError(ex, "获取网站信息时网络请求失败: {Url}", url);
            }
            catch (Exception ex)
            {
                websiteInfo.ErrorMessage = $"获取网站信息失败: {ex.Message}";
                logger.LogError(ex, "获取网站信息时发生未知错误: {Url}", url);
            }

            return websiteInfo;
        }

        /// <summary>
        /// 获取网站标题
        /// </summary>
        /// <param name="doc">HTML文档</param>
        /// <param name="uri">网站URI</param>
        /// <returns>网站标题</returns>
        private static string GetWebsiteTitle(HtmlDocument doc, Uri uri)
        {
            // 尝试从title标签获取
            var titleNode = doc.DocumentNode.SelectSingleNode("//title");
            if (titleNode != null && !string.IsNullOrWhiteSpace(titleNode.InnerText))
            {
                return CleanText(titleNode.InnerText);
            }

            // 尝试从og:title获取
            var ogTitleNode = doc.DocumentNode.SelectSingleNode("//meta[@property='og:title']");
            if (ogTitleNode != null)
            {
                var content = ogTitleNode.GetAttributeValue("content", "");
                if (!string.IsNullOrWhiteSpace(content))
                {
                    return CleanText(content);
                }
            }

            // 尝试从twitter:title获取
            var twitterTitleNode = doc.DocumentNode.SelectSingleNode("//meta[@name='twitter:title']");
            if (twitterTitleNode != null)
            {
                var content = twitterTitleNode.GetAttributeValue("content", "");
                if (!string.IsNullOrWhiteSpace(content))
                {
                    return CleanText(content);
                }
            }

            // 如果都没有，使用域名
            return uri.Host;
        }

        /// <summary>
        /// 获取网站描述
        /// </summary>
        /// <param name="doc">HTML文档</param>
        /// <returns>网站描述</returns>
        private static string GetWebsiteDescription(HtmlDocument doc)
        {
            // 尝试从meta description获取
            var descNode = doc.DocumentNode.SelectSingleNode("//meta[@name='description']");
            if (descNode != null)
            {
                var content = descNode.GetAttributeValue("content", "");
                if (!string.IsNullOrWhiteSpace(content))
                {
                    return CleanText(content);
                }
            }

            // 尝试从og:description获取
            var ogDescNode = doc.DocumentNode.SelectSingleNode("//meta[@property='og:description']");
            if (ogDescNode != null)
            {
                var content = ogDescNode.GetAttributeValue("content", "");
                if (!string.IsNullOrWhiteSpace(content))
                {
                    return CleanText(content);
                }
            }

            // 尝试从twitter:description获取
            var twitterDescNode = doc.DocumentNode.SelectSingleNode("//meta[@name='twitter:description']");
            if (twitterDescNode != null)
            {
                var content = twitterDescNode.GetAttributeValue("content", "");
                if (!string.IsNullOrWhiteSpace(content))
                {
                    return CleanText(content);
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 获取网站图标
        /// </summary>
        /// <param name="doc">HTML文档</param>
        /// <param name="uri">网站URI</param>
        /// <returns>图标URL</returns>
        private async Task<string> GetWebsiteIconAsync(HtmlDocument doc, Uri uri)
        {
            var iconUrls = new List<string>();

            // 尝试从link标签获取各种图标
            var iconNodes = doc.DocumentNode.SelectNodes("//link[@rel='icon' or @rel='shortcut icon' or @rel='apple-touch-icon' or contains(@rel, 'icon')]");
            if (iconNodes != null)
            {
                foreach (var node in iconNodes)
                {
                    var href = node.GetAttributeValue("href", "");
                    if (!string.IsNullOrWhiteSpace(href))
                    {
                        iconUrls.Add(href);
                    }
                }
            }

            // 添加默认favicon.ico路径
            iconUrls.Add("/favicon.ico");

            // 验证图标URL
            foreach (var iconUrl in iconUrls)
            {
                try
                {
                    var fullIconUrl = new Uri(uri, iconUrl).ToString();
                    
                    // 确保使用HTTPS协议以避免混合内容问题
                    fullIconUrl = EnsureHttpsUrl(fullIconUrl);
                    
                    // 检查图标是否可访问
                    var response = await httpClient.GetAsync(fullIconUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        var contentType = response.Content.Headers.ContentType?.MediaType;
                        if (contentType != null && contentType.StartsWith("image/"))
                        {
                            return fullIconUrl;
                        }
                    }
                }
                catch
                {
                    // 忽略错误，继续尝试下一个
                }
            }

            return string.Empty;
        }

        /// <summary>
        /// 确保URL使用HTTPS协议，避免混合内容问题
        /// </summary>
        /// <param name="url">原始URL</param>
        /// <returns>HTTPS URL</returns>
        private static string EnsureHttpsUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return url;

            // 如果是HTTP协议，转换为HTTPS
            if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                return "https://" + url.Substring(7);
            }

            // 如果是协议相对URL，添加HTTPS
            if (url.StartsWith("//"))
            {
                return "https:" + url;
            }

            return url;
        }

        /// <summary>
        /// 清理文本内容
        /// </summary>
        /// <param name="text">原始文本</param>
        /// <returns>清理后的文本</returns>
        private static string CleanText(string text)
        {
            if (string.IsNullOrWhiteSpace(text))
                return string.Empty;

            // 移除HTML标签
            text = Regex.Replace(text, "<.*?>", string.Empty);
            
            // 移除多余的空白字符
            text = Regex.Replace(text, @"\s+", " ");
            
            // 移除首尾空白
            text = text.Trim();

            // 限制长度
            if (text.Length > 200)
            {
                text = text.Substring(0, 200) + "...";
            }

            return text;
        }

        /// <summary>
        /// 获取网站主要内容
        /// </summary>
        /// <param name="doc">HTML文档</param>
        /// <returns>网站内容文本</returns>
        private static string GetWebsiteContent(HtmlDocument doc)
        {
            try
            {
                // 移除脚本和样式标签
                var scriptsAndStyles = doc.DocumentNode.SelectNodes("//script | //style | //noscript");
                if (scriptsAndStyles != null)
                {
                    foreach (var node in scriptsAndStyles)
                    {
                        node.Remove();
                    }
                }

                // 尝试获取主要内容区域
                var contentSelectors = new[]
                {
                    "//main",
                    "//article",
                    "//*[@id='content']",
                    "//*[@class='content']",
                    "//*[@id='main']",
                    "//*[@class='main']",
                    "//body"
                };

                string content = "";
                foreach (var selector in contentSelectors)
                {
                    var contentNode = doc.DocumentNode.SelectSingleNode(selector);
                    if (contentNode != null)
                    {
                        content = contentNode.InnerText;
                        break;
                    }
                }

                if (string.IsNullOrEmpty(content))
                {
                    // 如果没有找到主要内容，使用body的文本
                    var bodyNode = doc.DocumentNode.SelectSingleNode("//body");
                    content = bodyNode?.InnerText ?? "";
                }

                // 清理文本
                content = Regex.Replace(content, @"\s+", " ");
                content = content.Trim();

                // 限制长度（用于AI分析）
                if (content.Length > 5000)
                {
                    content = content.Substring(0, 5000);
                }

                return content;
            }
            catch (Exception)
            {
                return "";
            }
        }

        /// <summary>
        /// 仅获取网站图标
        /// </summary>
        /// <param name="url">网站URL</param>
        /// <returns>仅包含图标URL的网站信息</returns>
        public async Task<WebsiteInfo?> GetIconOnlyAsync(string url)
        {
            try
            {
                // 验证和标准化URL
                if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
                {
                    // 尝试添加http://前缀
                    if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                    {
                        url = "https://" + url; // 优先使用HTTPS
                        if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
                        {
                            // 如果HTTPS失败，尝试HTTP
                            url = "http://" + url.Substring(8);
                            if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
                            {
                                return null;
                            }
                        }
                    }
                    else
                    {
                        return null;
                    }
                }

                // 创建结果对象
                var websiteInfo = new WebsiteInfo
                {
                    Success = true
                };

                try
                {
                    // 获取网页内容
                    var response = await httpClient.GetAsync(uri);
                    if (!response.IsSuccessStatusCode)
                    {
                        return null;
                    }

                    var html = await response.Content.ReadAsStringAsync();
                    
                    // 解析HTML
                    var doc = new HtmlDocument();
                    doc.LoadHtml(html);

                    // 获取网站图标
                    websiteInfo.IconUrl = await GetWebsiteIconAsync(doc, uri);
                    
                    return websiteInfo;
                }
                catch (Exception)
                {
                    // 发生异常时尝试直接获取favicon.ico
                    try
                    {
                        var iconUri = new Uri(uri, "/favicon.ico");
                        var iconUrl = EnsureHttpsUrl(iconUri.ToString()); // 确保使用HTTPS
                        var iconResponse = await httpClient.GetAsync(iconUrl);
                        if (iconResponse.IsSuccessStatusCode)
                        {
                            var contentType = iconResponse.Content.Headers.ContentType?.MediaType;
                            if (contentType != null && contentType.StartsWith("image/"))
                            {
                                websiteInfo.IconUrl = iconUrl;
                                return websiteInfo;
                            }
                        }
                    }
                    catch
                    {
                        // 忽略错误
                    }
                }

                return null;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "获取网站图标时发生错误: {Url}", url);
                return null;
            }
        }
    }
} 